import type { Draft } from 'immer';
const eventMaps = new WeakMap();

export type DAction = {
  type: string;
  payload?: unknown;
};

export class UpdateReducer<IState, IAction = DAction> {
  static of() {
    return new UpdateReducer();
  }

  constructor() {
    eventMaps.set(this, {});
  }

  on(type: IAction['type'], callback: (draft: Draft<IState>, payload: IAction['payload']) => void) {
    eventMaps.get(this)[type] = callback;

    return this;
  }

  dispatch(draft: Draft<IState>, action: IAction) {
    const callback = eventMaps.get(this)[action.type];

    if (callback) {
      callback(draft, action.payload);
    }
  }
}
